<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.cleanbing.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Cleanbing <cleanbing@qq.com> <http://www.cleanbing.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;
use Think\Controller;

/**
 * APP控制器
 * 主要用于网站各种应用，如公司介绍，团队介绍，在线咨询，互动游戏等等
 */
class AppController extends HomeController {

	//APP首页
    public function index( $appName="" ){
    	$appName || $this->error("访问错误！");

    	$appData = $this->getAppData( $appName );
    	$this->assign( "data", $appData );

  		$appPath = CONTROLLER_NAME . "/" . $appName;
  		$viewRoot =  'Application/Home/View/' . C('DEFAULT_THEME') . "/" . $appPath;
  		$this->assign( "viewRoot", $viewRoot );

  		$this->display( $appPath . "/index" );
    }

    /*
    * 获取APP数据，可通过参数指定page, key, name=>value
    */
    private function getAppData( $appName="", $p = 0 ){
	    //获取模型信息
	    $model = M('Model')->getByName($appName);
	    $model || $this->error('模型不存在！');

      $page = intval($p);
      $page = $page ? $page : 1; //默认显示第一页数据
      $map	=	array();
      $key	=	$model['search_key']?$model['search_key']:'title';
      if(isset($_REQUEST[$key])){
          $map[$key]	=	array('like','%'.$_GET[$key].'%');
          unset($_REQUEST[$key]);
      }
      // 条件搜索
      foreach($_REQUEST as $name=>$val){
          if(in_array($name,$fields)){
              $map[$name]	=	$val;
          }
      }

      if($model['need_pk']){
          in_array('id', $fields) || array_push($fields, 'id');
      }
      $name = parse_name(get_table_name($model['id']), true);
      $data = M($name)
          /* 查询指定字段，不指定则查询所有字段 */
          ->field(true)
          // 查询条件
          ->where($map)
          /* 默认通过id逆序排列 */
          ->order($model['need_pk']?'id ASC':'')
          /* 数据分页 */
          ->page($page, $row)
          /* 执行查询 */
          ->select();

      /* 查询记录总数 */
      $count = M($name)->where($map)->count();
      return( $data );

    }//end of function
}//end of class